package com.saint.swipemenulistview.http;

import com.saint.swipemenulistview.courier.BaseConstant;

import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2017/12/27.
 */

public class HttpUtil {
    private static HttpService httpService;
    private static OkHttpClient.Builder client;

    public static HttpService getInstance() {
        synchronized (HttpUtil.class) {
            if (null == httpService) {
                initOkHttpClient();
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(BaseConstant.BASE_URL)
                        .addConverterFactory(ScalarsConverterFactory.create())
                        .client(client.build())
                        .build();

                httpService = retrofit.create(HttpService.class);
            }
        }
        return httpService;
    }

    /**
     * 配置请求参数方法
     *
     * @param postParams 请求参数
     * @return 排序并加上签名的map集合
     */
    public static HashMap<String, String> getParamMap(HashMap<String, String> postParams) {
        return getParamMap(postParams, false);
    }


    /**
     * 配置请求参数方法
     *
     * @param map 请求参数
     * @param sso 是否校验单点登录，默认false
     * @return 排序并加上签名的map集合
     */
    public static HashMap<String, String> getParamMap(HashMap<String, String> map, boolean sso) {
        map.put("appkey", "1");
        map.put("timestamp", System.currentTimeMillis() / 1000 + "");
        map.put("format", "json");
        map.put("version", "1.0.0");
        map.put("apiversion", "V1");
        map.put("device", "1");
        map.put("source", "ceshi");
        String name = strToMD5(getSortMap(map));
        map.put("sign", name);
//        MyLog.e(TAG, "签名:" + name);
        return map;
    }

    /**
     * 对请求参数排序，根据密钥进行Md5加密
     *
     * @param map 请求map
     * @return 加密后字符串
     */
    public static String getSortMap(Map<String, String> map) {
        String str = BaseConstant.SECRETKEY;
        Collection<String> keyset = map.keySet();
        List<String> list = new ArrayList<>(keyset);
        //对key键值按字典升序排序
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            str += list.get(i) + map.get(list.get(i));
        }
        str += BaseConstant.SECRETKEY;
        return str;
    }

    /**
     * 设置OkHttpClient 忽略https验证
     */
    private static void initOkHttpClient() {
        client = new OkHttpClient.Builder();

        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");

            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
            client.sslSocketFactory(sslContext.getSocketFactory());
            client.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

    }

    //使用MD5加密
    public static String strToMD5(String info) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();

            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++) {
                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }

            return strBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

}
